#include "gtest/gtest.h"
#include "Poller/Pipe.h"
#include "Util/util.h"
#include "Thread/threadgroup.h"
#include <atomic>

using namespace toolkit;
using namespace std;

TEST(PipeTest, basic) {
    // 测试构造函数和基本功能
    auto poller = EventPollerPool::Instance().getPoller();
    atomic<bool> read_flag{false};
    
    // 创建带回调的Pipe
    Pipe pipe([&](int size, const char *buf) {
        EXPECT_EQ(size, 5);
        EXPECT_STREQ(buf, "hello");
        read_flag = true;
    }, poller);

    // 发送数据
    pipe.send("hello", 5);

    // 等待回调执行
    int i = 0;
    while (!read_flag && i++ < 100) {
        usleep(10000);
    }
    EXPECT_TRUE(read_flag);
}

TEST(PipeTest, multiThread) {
    // 测试多线程场景
    atomic<int> read_count{0};
    Pipe pipe([&](int size, const char *buf) {
        read_count++;
    });

    thread_group group;
    for (int i = 0; i < 10; ++i) {
        group.create_thread([&]() {
            for (int j = 0; j < 100; ++j) {
                pipe.send("test", 4);
                usleep(1000);
            }
        });
    }
    group.join_all();

    // 等待所有消息处理完成
    int i = 0;
    while (read_count < 1000 && i++ < 100) {
        usleep(10000);
    }
    EXPECT_EQ(read_count, 1000);
}

TEST(PipeTest, defaultPoller) {
    // 测试默认事件轮询器
    atomic<bool> read_flag{false};
    Pipe pipe([&](int size, const char *buf) {
        read_flag = true;
    });

    pipe.send("test", 4);

    int i = 0;
    while (!read_flag && i++ < 100) {
        usleep(10000);
    }
    EXPECT_TRUE(read_flag);
}